package com.ch.ch7_2.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import com.ch.ch7_2.model.MyFile;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class TestFileUpload {
    /**
     * 进入文件选择页面
     */
    @RequestMapping("/uploadFile")
    public String uploadFile() {
        return "uploadFile";
    }
    /**
     * 上传文件自动绑定到MultipartFile对象中，在这里使用处理方法的形参接收请求参数。
     */
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, @RequestParam("description") String description,
                         @RequestParam("myfile") MultipartFile myfile) throws IllegalStateException, IOException {
        //如果选择了上传文件，将文件上传到指定的目录uploadFiles
        if(!myfile.isEmpty()) {
            //上传文件路径
            String path = request.getServletContext().getRealPath("/uploadFiles/");
            //获得上传文件原名
            String fileName = myfile.getOriginalFilename();
            File filePath = new File(path + File.separator + fileName);
            //如果文件目录不存在，创建目录
            if(!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件中
            myfile.transferTo(filePath);
        }
        //转发到一个请求处理方法，查询将要下载的文件
        return "forward:/showDownLoad";
    }
    /**
     * 显示要下载的文件
     */
    @RequestMapping("/showDownLoad")
    public String showDownLoad(HttpServletRequest request, Model model) {
        String path = request.getServletContext().getRealPath("/uploadFiles/");
        File fileDir = new File(path);
        //从指定目录获得文件列表
        File filesList[] = fileDir.listFiles();
        ArrayList<MyFile> myList = new ArrayList<MyFile>();
        for (int i = 0; i < filesList.length; i++) {
            MyFile mf = new MyFile();
            mf.setFno(i + 1);
            mf.setFname(filesList[i].getName());
            myList.add(mf);
        }
        model.addAttribute("filesList", myList);
        return "showFile";
    }
    /**
     * 实现下载功能
     */
    @RequestMapping("/download")
    public void download(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam("filename") String filename) throws IOException {
        //下载文件路径
        String path = request.getServletContext().getRealPath("/uploadFiles/");
        //构建将要下载的文件对象
        File downFile = new File(path + File.separator + filename);
        //使用URLEncoder.encode对文件名进行编码
        filename = URLEncoder.encode(filename,"UTF-8");
        response.setHeader("Content-Type", "application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        FileInputStream in = null; // 输入流
        ServletOutputStream out = null; // 输出流
        // 读入文件
        in = new FileInputStream(downFile);
        // 得到响应对象的输出流，用于向客户端输出二进制数据
        out = response.getOutputStream();
        out.flush();
        int aRead = 0;
        byte b[] = new byte[1024];
        while ((aRead = in.read(b)) != -1 & in != null) {
            out.write(b, 0, aRead);
        }
        out.flush();
        in.close();
        out.close();
    }
}
